<template>
  <!-- 新增参数 表单 -->
  <a-modal
    v-model:open="visible"
    title="通讯协议信息"
    @ok="handleOk"
    destroyOnClose
    :width="1200"
    @cancel="cancel"
    centered
  >
    <div class="nameContent">
      通讯协议用户名：<span v-if="!showEditName">{{
        mqttUserInfo?.username || "-"
      }}</span>
      <a-input
        v-model="userName"
        v-if="showEditName"
        class="nameInput"
        placeholder="请输入"
      />
      <!-- <EditOutlined
        @click="handleEditName"
        v-if="!showEditName"
        class="editIcon"
      />
      <CheckOutlined
        @click="handleSaveName"
        v-if="showEditName"
        class="editIcon"
      /> -->
    </div>
    <a-table
      :columns="columns"
      :data-source="tableData"
      bordered
      :pagination="false"
      :scroll="{ x: 'max-content' }"
      @resizeColumn="handleResizeColumn"
    >
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'linkName'">
          <div>
            <a-select
              v-if="record.isEdit"
              ref="select"
              show-search
              v-model:value="record.linkId"
              class="formInput"
              placeholder="请选择"
              allow-clear
              @change="getIdx(record, index)"
            >
              <a-select-option
                v-for="item in energyList"
                :key="item.deviceId"
                :value="item.deviceId"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <!--  -->
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-if="column.dataIndex === 'type'">
          <div>
            <a-select
              v-model:value="record.type"
              v-if="record.isEdit"
              class="formInput"
              placeholder="请选择"
              allow-clear
              @change="getIdx(record, index)"
            >
              <a-select-option :value="1"> 电池堆 </a-select-option>
              <a-select-option :value="2"> 电表 </a-select-option>
            </a-select>
            <template v-else>
              {{ text === 1 ? "电池堆" : "电表" }}
            </template>
          </div>
        </template>
        <template v-if="column.dataIndex === 'idx'">
          <div>
            <a-input
              v-model:value="record.idx"
              v-if="record.isEdit"
              class="formInput"
              placeholder="请输入"
              allow-clear
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-if="column.dataIndex === 'clientId'">
          <div>
            <a-input
              v-model:value="record.clientId"
              v-if="record.isEdit"
              class="formInput"
              placeholder="请输入"
              allow-clear
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-if="column.dataIndex === 'pubTopic'">
          <div>
            <a-input
              v-model:value="record.pubTopic"
              v-if="record.isEdit"
              class="formInput"
              placeholder="请输入"
              allow-clear
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-if="column.dataIndex === 'subTopic'">
          <div>
            <a-input
              v-model:value="record.subTopic"
              v-if="record.isEdit"
              class="formInput"
              placeholder="请输入"
              allow-clear
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-if="column.dataIndex === 'handle'">
          <div class="editable-row-operations">
            <span v-if="record.isEdit">
              <a-button type="link" @click="saveData(record, index)"
                >保存</a-button
              >
            </span>
            <span v-else>
              <a-button type="link" @click="editData(record, index)"
                >编辑</a-button
              >
            </span>
            <a-popconfirm
              ok-text="确认"
              cancel-text="取消"
              @confirm="confirmDel(record, index)"
            >
              <template #title>
                {{ `是否确定删除该条数据？` }}
              </template>
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
            <a-button
              v-hasPermission="'messageInfo'"
              v-if="record.id"
              type="link"
              class="messageBtn"
              @click="handleMessage(record)"
              >报文</a-button
            >
          </div>
        </template>
      </template>
    </a-table>
    <div class="addBtn">
      <div class="btn" @click="handleAdd"><PlusOutlined />新增</div>
    </div>
    <template #footer>
      <div class="footerBar">
        <a-button type="primary" @click="handleUserInfo">编辑</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          class="greenBtn"
          @click="handleExport"
          >导出</a-button
        >
      </div>
    </template>
  </a-modal>

  <!-- 通讯协议 -->
  <UserInfo
    :userInfoVisible="userInfoVisible"
    :rowData="props.rowData"
    :mqttUserInfo="mqttUserInfo"
    @update:userInfoVisible="(val) => (userInfoVisible = val)"
    @getMqttUserDetails="getMqttUserDetails"
  />

  <!-- 报文解析弹窗 -->
  <MessageParseModal
    :messageParseVisible="messageParseVisible"
    :rowData="currentRowData"
    @update:messageParseVisible="(val) => (messageParseVisible = val)"
  />
</template>
<script setup>


import UserInfo from "./userInfo/index.vue";
import MessageParseModal from "./MessageParseModal.vue";
import utilsExportFile from "@/utils/exportFile";
const $api = inject("$api");
const props = defineProps({
  protocolVisible: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
});
const visible = ref(props.protocolVisible);
const emits = defineEmits(["update:protocolVisible", "getParamCodePage"]);
const userInfoVisible = ref(false);
const messageParseVisible = ref(false);
const currentRowData = ref({});
const userName = ref("");
const mqttUserInfo = ref([]); // mqtt用户信息
const tableData = ref([]);
const isEdit = ref(false);
function handleResizeColumn(w, col) {
  col.width = w;
}
const columns = ref([
  {
    title: "电池堆名称",
    dataIndex: "linkName",
    key: "linkName",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "通讯设备类型",
    dataIndex: "type",
    key: "type",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "设备序列号/结算电表id",
    dataIndex: "idx",
    key: "idx",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "客户端ID",
    dataIndex: "clientId",
    key: "clientId",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "发布主题",
    dataIndex: "pubTopic",
    key: "pubTopic",
    width: 250,
    resizable: true,
    align: "center",
  },
  {
    title: "订阅主题",
    dataIndex: "subTopic",
    key: "subTopic",
    width: 250,
    resizable: true,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 160,
    resizable: true,
    align: "center",
    fixed: "right",
  },
]);
watch(
  () => props.protocolVisible,
  (val) => {
    visible.value = val;
    if (val) {
      getMqttAclNewPage();
      getEnergyLink();
      getMqttUserDetails();
    }
  }
);
const labelCol = { style: { width: "100px" } };
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
});
const cancel = () => {
  emits("update:protocolVisible", false);
};
const loading = ref(false);
const handleSubmit = () => {};
const showEditName = ref(false);
const handleEditName = () => {
  showEditName.value = !showEditName.value;
};
const handleSaveName = () => {
  handleEditName();
};
const confirmDel = async (data, index) => {
  if (!data.id) {
    // 删除时无id，即删除刚新增无保存的数据
    tableData.value.splice(index, 1);
  } else {
    const res = await $api.mqttAclNewDel([data.id]);
    if (res && res.code === 0) {
      message.success("删除成功");
      getMqttAclNewPage();
    }
  }
};
const handleAdd = () => {
  isEdit.value = false;
  tableData.value.push({
    key: tableData.value.length + 1,
    name: "",
    age: "",
    address: "",
    isEdit: true,
  });
};
const editData = (data, index) => {
  isEdit.value = true;
  for (const item of tableData.value) {
    item.isEdit = false;
  }
  tableData.value.filter((item) => data.key === item.key)[index].isEdit = true;
};
const saveData = async (data, index) => {
  tableData.value.filter((item) => data.key === item.key)[index].isEdit = false;
  const params = {
    ...data,
  };
  const res = await $api.mqttAclNew(params, isEdit.value ? "put" : "post");
  if (res && res.code === 0) {
    message.success(isEdit.value ? "编辑成功" : "新增成功");
    getMqttAclNewPage();
  }
};
const energyList = ref([]);
const getEnergyLink = async () => {
  const res = await $api.energyLinkPage({
    stationId: props.rowData.stationId,
  });
  energyList.value = res?.data?.records;
};
const getMqttAclNewPage = async () => {
  const res = await $api.mqttAclNewPage(props.rowData.stationId);
  if (res && res.code === 0) {
    tableData.value = res?.data;
  }
};
const handleUserInfo = () => {
  userInfoVisible.value = true;
};
const handleExport = async () => {
  const res = await $api.mqttUserExport(props.rowData.stationId);
  utilsExportFile.exportFile(
    res,
    `${mqttUserInfo.value?.username || "通讯协议"}.xlsx`
  );
};
const getMqttUserDetails = async (stationId) => {
  const res = await $api.mqttUserDetails(props.rowData.stationId);
  mqttUserInfo.value = res?.data;
};
const getIdx = async (data, index) => {
  const { linkId, type } = data;
  if (linkId && type) {
    const params = {
      stationId: props.rowData.stationId,
      linkId: data.linkId,
      type: data.type,
    };
    const res = await $api.mqttAclNewIdx(params);
    if (res.code === 0 && res.data) {
      tableData.value[index].idx = res.data;
    }
  }
};
const handleMessage = (data) => {
  currentRowData.value = data;
  messageParseVisible.value = true;
};
</script>

<style lang="less" scoped>
.nameContent {
  margin: 30px 0 20px 0;
}

.nameInput {
  width: 200px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.editIcon {
  margin-left: 8px;
}
.addBtn {
  margin: 10px 10px 10px 0;
  text-align: right;
  .btn {
    cursor: pointer;
    width: 50px;
    display: inline-block;
    color: #1668dc;
  }
}
.formInput {
  width: 100%;
  text-align: center;
}
.messageBtn {
  color: #a77730;
  &:hover {
    color: #b88738;
  }
}
</style>